<template>
  <div class="scroll-view">
    <div class="content" v-loading="pageLoading">
      <p class="title">轮播图</p>
      <div class="swiper-box flex ac fw">
        <el-upload v-if="$isPer(permission, ['miniProgram_addBanner'])" :show-file-list="false" :auto-upload="false"
          class="avatar-uploader banner" accept="image/*" action="#" :on-change="bannerChange">
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <div class="file-box" v-for="(item, index) in carousel_image" :key="index">
          <div class="edit-box" v-if="$isPer(permission, ['miniProgram_delBanner'])">
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <i class="iconfont icon-shanchu" @click="del('banner', item.id)"></i>
            </el-tooltip>
          </div>
          <el-image class="img" fit="cover" :src="item.file_url" :preview-src-list="bannerList"></el-image>
        </div>
      </div>
      <p class="title" style="margin-top: 25px;">精选案例</p>
      <div class="swiper-box flex fw " style="margin-bottom: 25px;">
        <div class="case-add" @click="dialogVisible = true;" v-if="$isPer(permission, ['miniProgram_addCase'])">
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </div>

        <div class="case-box" v-for="(item, index) in caseList" :key="index">
          <div class="file-box" @click.stop="$fileViewHandle(item.case_list[0])">
            <div class="edit-box"
              v-if="$isPer(permission, ['miniProgram_delCase']) || $isPer(permission, ['miniProgram_editCase'])">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top"
                v-if="$isPer(permission, ['miniProgram_editCase'])">
                <i class="iconfont icon-bianji1" @click.stop="edit(item)"></i>
              </el-tooltip>

              <el-tooltip class="item" effect="dark" content="删除" placement="top"
                v-if="$isPer(permission, ['miniProgram_delCase'])">
                <i class="iconfont icon-shanchu" @click.stop="del('case', item.id)"></i>
              </el-tooltip>
            </div>
            <div class="play" v-if="item.file_type == 2">
              <i class="el-icon-caret-right"></i>
            </div>
            <video v-if="item.file_type == 2" class="img" fit="cover" :src="item.case_list[0].file_url"></video>
            <el-image v-else class="img" fit="cover" :src="item.case_list[0].file_url"></el-image>
          </div>
          <div class="case-title">{{ item.title }}</div>
        </div>
      </div>
      <p class="title">公司介绍</p>
      <div class="tinymce-box flex">
        <tinymce @input="tinymceInput" :value="introductionContent"></tinymce>
        <div class="html-box" v-html="richText"></div>
      </div>
      <el-button type="primary" @click="addOrUpdIntroduction" :loading="pageLoading"
        v-if="$isPer(permission, ['miniProgram_saveDesc'])">保存公司简介</el-button>
    </div>
    <!-- 添加 -->
    <el-dialog :title="formInline.id ? '修改案例' : '添加案例'" :visible.sync="dialogVisible" width="500px"
      :before-close="handleClose">
      <el-form :model="formInline" ref="ruleForm" :rules="rules" class="demo-form-inline" label-width="80px"
        label-position="left">
        <el-form-item label="案例名称" prop="title">
          <el-input v-model="formInline.title" placeholder="请输入案例名称"></el-input>
        </el-form-item>
        <el-form-item label="上传类型" prop="file_type">
          <el-radio-group v-model="formInline.file_type" @input="radioChange" :disabled="!!formInline.id">
            <el-radio :label="1">图片</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传文件" prop="fileList">
          <div class="upload-file-box">
            <template v-if="formInline.fileList.length != 0 && formInline.file_type == 1">
              <div class="upload-box" v-for="(item, index) in formInline.fileList" :key="index">
                <img class="upload-img" :src="item.url" />
                <i class="el-icon-delete" @click.stop="filedel(item)"></i>
              </div>
            </template>
            <template v-if="formInline.fileList.length != 0 && formInline.file_type == 2">
              <div class="upload-box">
                <video class="upload-viedo" :src="formInline.fileList[0].url"></video>
                <i class="el-icon-delete" @click.stop="filedel(formInline.fileList[0])"></i>
              </div>
            </template>

            <el-upload class="avatar-uploader" ref="upload" action="#"
              v-show="(formInline.file_type == 1 && formInline.fileList.length < 9) || (formInline.file_type == 2 && formInline.fileList.length == 0)"
              :show-file-list="false" :multiple="formInline.file_type == 1 ? true : false"
              :accept="formInline.file_type == 1 ? 'image/*' : 'video/*'" :limit="formInline.file_type == 1 ? 9 : 1"
              list-type="picture-card" :auto-upload="false" :on-change="fileChange">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="submitFunc('ruleForm')" :loading="pageLoading">
          {{ formInline.id ? '修 改' : '添 加' }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from "@/components/tinymce/tinymce";
import miniApi from '@/api/mini'
export default {
  name: 'miniProgramManagement',
  components: {
    Tinymce
  },
  data() {
    const fileRule = (rule, value, callback) => {
      if (!this.formInline.fileList || this.formInline.fileList.length <= 0) {
        callback(new Error('请上传文件'))
      } else {
        callback()
      }
    }
    return {
      richText: '',
      dialogVisible: false,
      formInline: {
        file_type: 1,
        fileList: [],
        title: '',
      },
      rules: {
        fileList: [{ required: true, trigger: 'change', validator: fileRule }],
        file_type: [{ required: true, trigger: 'change' }],
        title: [{ required: true, trigger: 'change', message: '请输入案例名称' }],
      },
      caseList: [],
      pageLoading: false,
      carousel_image: [],
      bannerList: [],
      introductionContent: '',
      permission: [],//操作权限
    }
  },
  activated() {
    this.getWxConfig();
  },
  watch: {},
  computed: {

  },
  mounted() {
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.getWxConfig();
  },
  methods: {
    tinymceInput(e) {
      const regex = new RegExp('img', 'gi')
      e = e.replace(regex, `img style="max-width:100%;object-fit: cover;"`)
      this.richText = e;
    },
    handleClose() {
      this.formInline = {
        file_type: 1,
        fileList: [],
        title: '',
      }
      this.$nextTick(() => {
        this.$refs.upload.clearFiles();
        this.$refs.ruleForm.clearValidate();
        this.dialogVisible = false;
      })
    },
    radioChange() {
      this.formInline.fileList = [];
      this.$refs.upload.clearFiles();
    },
    fileChange(file, fileList) {
      // this.formInline.fileList = fileList
      this.formInline.fileList.push(file);
    },
    filedel(file) {
      if (this.formInline.fileList.length == 1) {
        this.$message.warning('案例至少要有一个文件');
        return;
      }
      if (file.id) {
        this.delCaseFile(file.id);
        return;
      }
      this.$refs.upload.handleRemove(file);
      this.formInline.fileList.forEach((item, index) => {
        if (item.url == file.url) {
          this.formInline.fileList.splice(index, 1)
        }
      })

    },
    // 删除案例里的文件
    delCaseFile(file_id) {
      let formInline = this.formInline;
      miniApi.delCaseFile({
        file_id
      }).then(res => {
        console.log(res, "删除案例里的文件")
        if (res.code == 200) {
          this.getWxConfig();
          let index = formInline.fileList.findIndex(item => {
            return item.id == file_id;
          })
          formInline.fileList.splice(index, 1);
          this.formInline = formInline;
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    submitFunc() {
      let formInline = this.formInline;
      console.log(formInline, "表单数据")
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (!formInline.fileList.length) {
            this.$message.warning('案例至少上传一个文件');
            return;
          }
          let obj = {
            file_type: formInline.file_type,
            title: formInline.title
          }
          let formdata = new FormData();
          formInline.fileList.forEach(item => {
            if (item.raw) {
              formdata.append('case_image[]', item.raw);
            }
          })
          if (formInline.id) {
            obj.id = formInline.id;
            formdata.append('data', JSON.stringify(obj));
            this.updCase(formdata);
            return;
          }
          // 添加
          formdata.append('data', JSON.stringify(obj));
          this.addCase(formdata);
        }
      })
    },
    // 更新案例
    updCase(data) {
      this.pageLoading = true;
      miniApi.updCase(data).then(res => {
        console.log(res, '更新案例')
        this.pageLoading = false;
        if (res.code == 200) {
          this.getWxConfig();
          this.handleClose();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      }).catch(err => {
        this.pageLoading = false;
      })
    },
    // 添加案例
    addCase(data) {
      this.pageLoading = true;
      miniApi.addCase(data).then(res => {
        console.log(res, "添加案例")
        this.pageLoading = false;
        if (res.code == 200) {
          this.getWxConfig();
          this.handleClose();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      }).catch(err => {
        this.pageLoading = false;
      })
    },
    edit(item) {
      console.log(item)
      let fileList = [];
      item.case_list.forEach(file => {
        file.url = file.file_url;
        fileList.push(file)
      })
      this.formInline = {
        id: item.id,
        file_type: item.file_type,
        title: item.title,
        fileList
      }
      console.log(this.formInline)
      this.dialogVisible = true
    },
    del(type, id) {
      if (type == 'banner') {
        var tips = '是否删除该轮播图?';
      } else {
        var tips = '是否删除该案例?';
      }
      this.$confirm(tips, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.delWxConfig(id);
      })
    },
    // 删除
    delWxConfig(id) {
      miniApi.delWxConfig({ id }).then(res => {
        console.log(res, "删除")
        if (res.code == 200) {
          this.getWxConfig();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // 获取小程序配置
    getWxConfig() {
      this.pageLoading = true;
      let bannerList = [];
      miniApi.getWxConfig().then(res => {
        console.log(res, "获取小程序配置")
        this.pageLoading = false;
        if (res.code == 200) {
          this.introductionContent = res.data.introduction.content;
          this.richText = res.data.introduction.content;
          this.carousel_image = res.data.carousel_image;
          this.caseList = res.data.case;
          res.data.carousel_image.forEach(item => {
            bannerList.push(item.file_url);
          })
          this.bannerList = bannerList;
        }
      }).catch(err => {
        this.pageLoading = false;
      })
    },
    // 添加轮播图
    bannerChange(e) {
      console.log(e)
      let formdata = new FormData();
      formdata.append('carousel_image', e.raw);
      this.addCarouselImage(formdata);
    },
    addCarouselImage(data) {
      this.pageLoading = true;
      miniApi.addCarouselImage(data).then(res => {
        console.log(res, "添加轮播图")
        this.pageLoading = false;
        if (res.code == 200) {
          this.getWxConfig();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      }).catch(err => {
        this.pageLoading = false;
      })
    },
    // 添加更新公司简介
    addOrUpdIntroduction() {
      this.pageLoading = true;
      let content = this.richText;
      miniApi.addOrUpdIntroduction({
        content
      }).then(res => {
        console.log(res, "更新公司简介")
        this.pageLoading = false;
        if (res.code == 200) {
          this.getWxConfig();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      }).catch(err => {
        this.pageLoading = false;
      })
    },
  }
}

</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
